<template>
  <div class="uni-login-register-wrap">
    <div class="uni-login-sign-in-btn" v-if="showType !== 'step-email'" @click="goSignIn"><i></i>{{ $tt('Sign In') }}
    </div>
    <!--创建账号-->
    <div class="uni-login-step uni-login-step-email" v-show="showType==='step-email'">
      <el-form>
        <el-form-item>
          <el-input v-model="registerForm.email" @input="_checkEmailInput" :placeholder="$tt('EMAIL')"></el-input>
          <ErrorTips class="uni-login-err-tip" :error-map="errorMap" v-show="errorMap.email"></ErrorTips>
        </el-form-item>
        <OtherLogin class="mt30" :subscribe_ad="registerForm.subscribe_ad" :before-go="checkAccept" :title="$tt('YOU CAN ALSO CREATE AN ACCOUNT WITH')"></OtherLogin>

        <el-form-item>
          <BaseCheckbox v-model="registerForm.subscribe_ad">
            {{ $tt('Receive news,special offers,feedback surveys,and playtest invitations from Wizard Games') }}
          </BaseCheckbox>
        </el-form-item>
        <el-form-item>
          <BaseCheckbox v-model="registerForm.accept" uid="accept" @change="clearError">
            <label for="accept">{{ $tt("I've read and accepted the") }} </label>
            <a :href="endUserLicenseAgreement" target="_blank" class="uni-login-color-blue">{{
                $tt('User Agreement')
              }}</a>
            <span> {{ $tt('and') }} </span>
            <a :href="privacyPolicy" target="_blank" class="uni-login-color-blue">{{ $tt('Privacy Policy') }}</a>
          </BaseCheckbox>
          <ErrorTips class="uni-login-err-tip" :error-map="errorMap" v-show="errorMap.accept"></ErrorTips>
        </el-form-item>
        <div class="uni-login-btn mb10 mt40"
             :class="{disabled: !isStepEmailReady}"
             @click="isStepEmailReady ? nextToPassword() : null">
          {{ $tt('NEXT') }}
        </div>
      </el-form>
      <CanNotSignIn></CanNotSignIn>
    </div>

    <!--设置密码-->
    <div class="uni-login-step uni-login-step-password" v-show="showType === 'step-password'">
      <div class="title-text">{{ $tt('SET A PASSWORD') }}</div>
      <el-form class="sign-form" :model="registerForm">
        <el-form-item prop="password" class="mb30">
          <el-input v-model="registerForm.password" :placeholder="$tt('PASSWORD')" type="password"
                    @blur="_checkPasswordInput"
                    @input="_checkRePasswordInput"
                    show-password></el-input>
          <ErrorTips class="uni-login-err-tip" :error-map="errorMap" prop="password"></ErrorTips>
        </el-form-item>
        <el-form-item prop="rePassword" class="mb30">
          <el-input v-model="registerForm.rePassword" :placeholder="$tt('CONFIRM PASSWORD')" type="password"
                    @input="_checkRePasswordInput"
                    show-password></el-input>
          <ErrorTips class="uni-login-err-tip" :error-map="errorMap" prop="rePassword"></ErrorTips>
        </el-form-item>
        <div class="uni-login-btn mt40                                                                                                                                                                                                                                                                                                                                                                                       " :class="{disabled: !isStepPasswordReady}"
             @click="isStepPasswordReady ? nextToCode() : null">{{ $tt('NEXT') }}
        </div>
      </el-form>
    </div>
    <!--验证码-->
    <div class="uni-login-step uni-login-step-code" v-show="showType === 'step-code'">
      <div class="title-text">{{ $tt('PLEASE CHECK YOUR EMAIL') }}</div>
      <div class="sub-title-text">
        {{ $tt('VERIFICATION CODE HAS BEEN SENT TO YOUR EMAIL,PLEASE ENTER TO COMPLETE THE REGISTRATION') }}
      </div>
      <div class="code mb30">
        <CodeInput v-model="registerForm.code" @input="onCodeChange"/>
      </div>
      <!--      <ErrorTips class="uni-login-err-tip" :error-map="errorMap"></ErrorTips>-->
      <div class="uni-login-btn mb20"
           :class="{disabled: !isStepRegisterReady}"
           @click="isStepRegisterReady ? submit() : null">
        {{ $tt("NEXT") }}
      </div>
      <div class="uni-login-code-tip">
        {{ $tt("HAVEN'T RECEIVED EMAIL?") }}
        <span :class="seconds === 60 ? 'uni-login-color-blue' : 'uni-login-color-gray'"
              @click="seconds === 60 ? sendMsg() : null">{{ $tt("CLICK HERE") }} </span>
        {{ $tt('TO RESEND') }} ({{ seconds }}s)
      </div>
      <div class="uni-login-email-tips">{{$tt("DON'T FORGET TO CHECK YOUR OTHER/SPAM/JUNK FOLDER FOR EMAIL VERIFICATION!")}}</div>
    </div>
    <!--注册成功-->
    <div class="uni-login-step uni-login-step-success" v-show="showType === 'step-success'">
      <div class="title-text">{{ $tt('YOU ARE ALMOST READY!') }}</div>
      <div class="sub-title-text">
        {{ $tt("YOU HAVE SUCCESSFULLY REGISTERED, AND GAINED ACCESS FOR BETA.YOU CAN DOWNLOAD THE GAME NOW FOR SPECIAL BETA TEST GIFTS!") }}
      </div>
<!--      app_key WEB端A0001, 客户端A0002-->
<!--      platform 网页平台 pc/mobile-->
<!--      scene 场景值：website 网站、member 会员中心、client 游戏客户端-->
<!--      * 只有web端-PC端-官网 展示下载按钮 *-->


      <a class="uni-login-btn mb20"
         v-if="$root.$options.props.show_download.type"
         :href="getEnv($root.$options.props.mode.type).websiteHost +'/' + $root.$options.props.language.type +  '/gameInfo/download'">
        {{$tt("DOWNLOAD THE GAME NOW") }}
      </a>
      <span class="uni-login-btn" @click="goSignIn" >
        {{$tt('Sign In')}}
      </span>
    </div>
  </div>
</template>

<script>
import BaseCheckbox from "@/componnets/BaseCheckbox";
import OtherLogin from "@/componnets/OtherLogin";
import CodeInput from "@/componnets/CodeInput";
import ErrorTips from "@/componnets/ErrorTips";
import CanNotSignIn from "@/componnets/CanNotSignIn";

import {register, checkEmailIsUsed, sendMessage, refreshClientToken} from "@/api";
import {isEmail, isPassword, encryptPassWord} from "@/utils";
import getEnv from "@/utils/env";
import {endUserLicenseAgreement, privacyPolicy} from '@/utils/links'

export default {
  components: {
    BaseCheckbox,
    OtherLogin,
    ErrorTips,
    CodeInput,
    CanNotSignIn

  },
  data() {
    return {
      // isAppointment: true, // 是否是预约
      endUserLicenseAgreement,
      privacyPolicy,
      getEnv,
      showType: 'step-email',
      // showType: 'step-code',
      // showType: 'step-success',
      registerForm: {
        server: '',
        email: '',
        password: '',
        rePassword: '',
        scene: 'website', // 场景值：website 网站、member 会员中心、client 游戏客户端
        app_key: 'A0001', // WEB端传A0001, 客户端传A0002
        code: '', // 邮件验证码
        from: '', // 广告位 默认website
        channel_id: '', // 大渠道ID
        channel_ad_id: '', // 广告位id
        sub_channel_id: '', // 子渠道
        third_party_type: '', // 三方登录类型 google、facebook
        third_party_account: '', // 三方open id
        subscribe_ad: false,
        accept: false,
        share_code: '' // 邀请码
      },
      nextToPasswordLock: false,
      registerLock: false,
      codeLock: false,
      errorMap: {
        robot: '',
        email: '',
        password: '',
        rePassword: '',
        code: '',
        accept: ''
      },
      timer: null,
      seconds: 60,

    }
  },
  watch: {
    'registerForm.code'() {
      this.errorMap.code = ''
    },
    'registerForm.password'() {
      this.errorMap.robot = ''
    },
    'registerForm.rePassword'() {
      this.errorMap.robot = ''
    }
  },
  mounted() {
      const {app_key, scene, share_code} = this.$root.$options.props;
      this.registerForm.scene = scene.type;
      this.registerForm.app_key = app_key.type;
      this.registerForm.share_code = share_code.type;
      this.registerForm = {...this.registerForm}
      console.log(this.registerForm)
  },
  computed: {
    isStepEmailReady() {
      return this.registerForm.email && this.registerForm.accept && !this.errorMap.email
    },
    isStepPasswordReady() {
      return this.registerForm.password && this.registerForm.rePassword && !this.errorMap.password && !this.errorMap.rePassword
    },
    isStepRegisterReady() {
      return !this.registerLock && this.registerForm.code.length >= 6
    },
    isStepCodeReady() {
      return this.registerForm.code.length >= 6
    },
  },
  methods: {
    checkAccept(){
      if(!this.registerForm.accept){
        this.errorMap.accept = this.$tt("Please make sure you have read and accepted the User Agreement and Privacy Policy")
        return false
      }else{
        return true
      }
    },
    clearError() {
      // this.errorMap.tips = ''
      this.errorMap.accept = ''
    },
    async nextToPassword() {
      if (this.nextToPasswordLock) return
      // try{
      //   const {code, msg} = await checkEmailIsUsed({email: this.registerForm.email})
      //   this.nextToPasswordLock = false
      //
      // }catch (e){
      //   this.nextToPasswordLock = false
      // }
      this.nextToPasswordLock = true
      checkEmailIsUsed({email: this.registerForm.email}).then(({code, msg}) => {
        this.nextToPasswordLock = false
        console.log(code)
        if (code === 420049) {
          this.errorMap.email = this.$tt('Email has been used')
        } else if (code === 0) {
          this.errorMap.email = ''
          this.showType = 'step-password'
          this.$parent.toggleTabVisible(false)
        } else {
          throw new Error(msg)
        }
      }).catch((err) => {
        this.nextToPasswordLock = false
        console.log(err)
      })
    },
    nextToCode() {
      // console.log('1')
      const _this = this

      // eslint-disable-next-line no-undef
      grecaptcha.ready(function () {
        // eslint-disable-next-line no-undef
        grecaptcha.execute(process.env.VUE_APP_RECAPTCHA_ID, {action: 'submit'}).then((token) => {
          // Add your logic to submit to your backend server here.
          console.log(token)
          //
          _this.sendMsg(token)
        })
      })

    },

    /**
     * 发送验证码
     */
    sendMsg(robotToken) {
      if (this.codeLock) return
      this.codeLock = true
      return sendMessage({
        token: robotToken,
        email: this.registerForm.email,
        type: 2 // 邮件类型 1登录 2注册 3绑定 4 解绑 5 忘记密码
      }).then(res => {
        this.showType = 'step-code'

        clearInterval(this.timer)
        if (res.code === 0) {
          this.timer = setInterval(() => {
            if (this.seconds > 0) {
              this.seconds -= 1
            } else {
              this.seconds = 60
              clearInterval(this.timer)
            }
          }, 1000)
        } else if (res.code === 430340) {
          this.errorMap.robot = this.$tt('You appear to be a robot, please retype again to try')
        }
        this.codeLock = false
      })

    },
    onCodeChange() {
      this.registerLock = false
    },
    /**
     * 提交
     */
    async submit() {
      if (this.registerLock) return
      this.registerLock = true

      let params = JSON.parse(JSON.stringify(this.registerForm))
      console.log(params)
      params.password = encryptPassWord(params.password)
      // 删除重复密码
      delete params.rePassword
      // 删除为空的参数
      Object.keys(params).forEach(key => {
        params[key] === '' ? delete params[key] : null
      })
      // 添加渠道信息
      this.$parent._addChannelInfo(params)
      register(params).then(async (res) => {
        console.log(res)
        if (res.code === 0) {
            if (this.$root.$options.props.app_key.type === 'A0002') {
                console.log(res.data.user_token, '---res.user_token----');
                const user = await refreshClientToken({
                    app_key: 'client'
                }, res.data.user_token);
                if (user.code === 0) {
                    this.nextToSuccess()
                    console.log(this.$parent.loginSuccess);
                    this.$parent.loginSuccess(user.data);
                    this.registerLock = false
                }
            } else {
                this.nextToSuccess()
                this.$parent.registerSuccess(res);
                this.registerLock = false
            }
        } else if (res.code === 430145) { // 验证码错误
          // this.registerLock = true
        } else {
          this.registerLock = false
        }
      }).catch(() => {
        this.registerLock = false
      })
    },
    nextToSuccess() {
      this.showType = 'step-success'
    },

    //  _checkEmailInput: debounce(async function () {
    //   if(!this.registerForm.email) {
    //     this.errorMap.email = ''
    //   }else if (isEmail(this.registerForm.email)) {
    //     // const {code, msg} = await checkEmailIsUsed({email: this.registerForm.email})
    //     // console.log(code)
    //     // if (code === 420049) {
    //     //   this.errorMap.email = this.$tt('Email has been used')
    //     // } else if (code === 0) {
    //       this.errorMap.email = ''
    //     // } else {
    //     //   throw new Error(msg)
    //     // }
    //   } else {
    //     this.errorMap.email = this.$tt('Please enter a correct E-mail')
    //   }
    // }, 0),

    _checkEmailInput() {
      if (!this.registerForm.email) {
        this.errorMap.email = ''
      } else if (isEmail(this.registerForm.email)) {
        this.errorMap.email = ''
      } else {
        this.errorMap.email = this.$tt('Please enter a correct E-mail')
      }
    },
    _checkPasswordInput() {
      console.log(this.registerForm.password)
      if (!this.registerForm.password) {
        this.errorMap.password = ''
      } else if (isPassword(this.registerForm.password)) {
        this.errorMap.password = ''
      } else {
        this.errorMap.password = this.$tt('Password should be a combination of 8-16 digits and letters')
      }
      // // 如果确认密码有值 继续验证确认密码
      // if(this.registerForm.rePassword){
      //   this._checkRePasswordInput()
      // }
    },
    _checkRePasswordInput() {
      if (!this.registerForm.rePassword || !this.registerForm.password) {
        this.errorMap.rePassword = ''
      } else if (this.registerForm.rePassword === this.registerForm.password) {
        this.errorMap.rePassword = ''
      } else {
        this.errorMap.rePassword = this.$tt('Two passwords entered do not match')
      }
    },
    _checkCodeInput() {
      // if(!this.registerForm.email) {
      this.errorMap.code = ''
      // }
    },
    goSignIn() {
      this.$parent.toggleTabVisible(true)
      this.$parent.toggleShowType('loginSdk')
    }

  },
  beforeDestroy() {
    clearInterval(this.timer)
  }
}
</script>
<style scoped lang="scss">

.uni-login-register-wrap {
  position: relative;
  padding-top: 30px;

  .uni-login-btn {
    display: block;
    color: #fff;
    height: 50px;
    line-height: 50px;
    cursor: pointer;
    border-radius: 4px;
    background: linear-gradient(120deg, #aa1726, #dc2133);
    text-align: center;
    transition: .3s;
    text-decoration: none;
    &:hover{
      filter: brightness(120%);
    }
    &.disabled {
      cursor: default;
      background: linear-gradient(120deg, #222, #1b1b1b);
      &:hover{
        filter: none;
      }
    }
  }

  .title-text {
    font-size: 32px;
    font-weight: 700;
    text-align: center;
    margin-bottom: 30px;
  }

  .sub-title-text {
    text-align: center;
    margin-bottom: 30px;
    font-size: 14px;
  }

  .uni-login-error-box {
    color: #E62335;
  }

  .uni-login-color-red {
    color: #E62335 !important;
  }

  .uni-login-color-blue {
    color: #0B89FF !important;
    cursor: pointer;
    text-decoration: underline;
  }

  .uni-login-email-tips{
    margin-top: 10px;
    color: #E62335 !important;
    font-size: 12px;
  }
  .uni-login-code-tip {
    .uni-login-color-gray {
      color: #999;
    }
  }

  .uni-login-sign-in-btn {
    position: absolute;
    cursor: pointer;
    top: -20px;
    left: -10px;
    width: 105px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #565A60;
    border-radius: 4px;
    text-align: center;
    height: 36px;

    i {
      display: inline-block;
      width: 9px;
      height: 14px;
      margin-right: 15px;
      background-image: url("@/assets/images/icon_arrow_back.png");
      background-size: cover;
    }
  }
}
.uni-login-err-tip {
  //position: relative;
  //top: -20px;
  //transform: translateY(-20px);
  height: 0;
}
</style>
